package cn.wolfcode.aspect;

import cn.wolfcode.JWTUtils;
import cn.wolfcode.domain.OperationLog;
import cn.wolfcode.mapper.OperationLogMapper;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

@Slf4j
@Aspect
@Component
public class LogAspect {
    @Autowired
    private HttpServletRequest httpServletRequest;
    @Autowired
    private JWTUtils jwtUtils;
    @Autowired
    private OperationLogMapper operationLogMapper;
    @Around("@annotation(cn.wolfcode.ann.MyLog)")
    public Object addLog(ProceedingJoinPoint pjp) throws Throwable {
        OperationLog oLog = new OperationLog();
        // 用户id
        /**
         * 获取 token 解析 token
         *
         */
        String token = httpServletRequest.getHeader("token");
        Claims claims = jwtUtils.parserJWT(token);
        int  userId = (int) claims.get("id");
        oLog.setUserId(Long.valueOf(userId));
        // 创建时间
        oLog.setCreatTime(new Date());
        // 操作类名
        String className = pjp.getTarget().getClass().getName();
        oLog.setClassName(className);
        // 方法名
        String methodName = pjp.getSignature().getName();
        oLog.setMethodName(methodName);
        // 方法参数
        Object[] args = pjp.getArgs();
        oLog.setMethodParam(Arrays.toString(args));
        // 方法返回值

        long begin = System.currentTimeMillis();
        Object proceed = pjp.proceed();
        long end = System.currentTimeMillis();
        String s = JSONObject.toJSONString(proceed);
        oLog.setMethodResult(s);
        // 操作时间
        oLog.setCountTime((int) (end-begin));
        operationLogMapper.add(oLog);
        return proceed;
    }
}
